using Microsoft.EntityFrameworkCore;
using WeatherMcpServer.Data.Entities;

namespace WeatherMcpServer.Data;

/// <summary>
/// EF Core 上下文：管理天气预警相关的实体与数据库映射。
/// </summary>
public class WeatherDbContext : DbContext
{
    /// <summary>
    /// 通过依赖注入传入的 DbContextOptions 构造函数。
    /// </summary>
    public WeatherDbContext(DbContextOptions<WeatherDbContext> options) : base(options)
    {
    }

    /// <summary>预警记录表</summary>
    public DbSet<WeatherAlert> WeatherAlerts => Set<WeatherAlert>();
    /// <summary>预警规则表</summary>
    public DbSet<WeatherRule> WeatherRules => Set<WeatherRule>();
    /// <summary>预警动作日志表</summary>
    public DbSet<WeatherAlertActionLog> WeatherAlertActionLogs => Set<WeatherAlertActionLog>();
    /// <summary>数据源抓取日志表</summary>
    public DbSet<WeatherSourceFetchLog> WeatherSourceFetchLogs => Set<WeatherSourceFetchLog>();

    /// <summary>
    /// 使用 Fluent API 配置字段长度、索引及约束，尽量与 MES 规范对齐。
    /// </summary>
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<WeatherAlert>(entity =>
        {
            // 字段长度与必填约束
            entity.Property(p => p.Source).HasMaxLength(50).IsRequired();
            entity.Property(p => p.RegionCode).HasMaxLength(32);
            entity.Property(p => p.RegionName).HasMaxLength(128);
            entity.Property(p => p.Message).HasMaxLength(512);
        });

        modelBuilder.Entity<WeatherRule>(entity =>
        {
            entity.Property(p => p.Description).HasMaxLength(256);
            entity.Property(p => p.RegionCode).HasMaxLength(32);
        });

        modelBuilder.Entity<WeatherAlertActionLog>(entity =>
        {
            entity.Property(p => p.Target).HasMaxLength(256);
            entity.Property(p => p.Result).HasMaxLength(512);
        });

        modelBuilder.Entity<WeatherSourceFetchLog>(entity =>
        {
            entity.Property(p => p.Source).HasMaxLength(50).IsRequired();
            entity.Property(p => p.RequestUrl).HasMaxLength(256);
            entity.Property(p => p.Error).HasMaxLength(1024);
        });
    }
}
